import webapp2
import cgi
from django.utils import simplejson


from models.beer import Beer
from models.kegdroid import KegDroid
from models.drinker import Drinker
from models.brewery import Brewery

################		
class DrinkerHandler(webapp2.RequestHandler):
	
	def post(self):
		drinker_name = cgi.escape(self.request.get('drinker_name'))
		if (drinker_name != ''):
			
			#last_drink
			#favorite_beer
			#google_account
			#google_plus_id
			kegdroids = cgi.escape(self.request.get('selected_kegdroid'))
			dkr = Drinker()
			dkr.name = drinker_name
			dkr.kegdroids = kegdroids
			dkr.put()
			newdkr = Drinker.all().filter('name =', drinker_name).get()
			dkrid = newdkr.key().id()
			self.redirect('/drinkers?id=' + str(dkrid))
			
		else:
			if (drinker_name == ''):
				self.response.out.write("<html><body><p>Missing name for drinker</p></body></html>")
			else: 
				self.response.out.write("<html><body><p>An Error Occured</p></body></html>")
	
	def get(self):
		tag = self.request.get('id')
		if (tag):
			if (tag == "all"):
				output = []
				drinkers = Drinker.all().order('name')
				for dkr in drinkers:
					output.append(dkr.to_dict())
				self.response.out.write(simplejson.dumps({'drinkers': output}).replace("\/", "/"))
			else:
				output = []
				dId = int(tag)
				if (dId > 0):
					dkr = Drinker.get_by_id(dId)
					if dkr != None:
						output.append(dkr.to_dict()) 
				self.response.out.write(simplejson.dumps({'drinker': output}).replace("\/", "/"))
		else :
			
			output = []
			drinkers = Drinker.all().order('name')
			for dkr in drinkers:
				output.append(dkr.to_dict())
			self.response.out.write(simplejson.dumps({'drinkers': output}).replace("\/", "/"))


################		
class AddDrinkerHandler(webapp2.RequestHandler):
	
	def get(self):

		kegdroid_list = ''
		kegdroids = KegDroid.all().order('name')
		for kd in kegdroids:
			kegdroid_list += '<div>'
			kegdroid_list += kd.name
			kegdroid_list += '<input type="checkbox" name=" '
			kegdroid_list += kd.name
			kegdroid_list += '" value="'
			kegdroid_list += str(kd.key().id())
			kegdroid_list += '" /></div>'
					
		self.response.out.write("""
				<html>
				<head>
				<meta charset="utf-8">
			    <title>KegDroid</title>
				<script src="http://code.jquery.com/jquery-1.8.3.min.js"></script>
				</head>
				<body>
			""")
		self.response.out.write( """
			<script>
			  $(document).ready(function(){

				function createList() {
					var t = "";
					$("input:checked").each( function(index) {
						t += $(this).val() + ', ' ;
					})
					var strLen = t.length;
					t = t.slice(0,-2);
					$('input[name="selected_kegdroid"]').val(t);
				}

			    function countChecked() {
					var n = $("input:checked").length;
			      	$('input[name="num_selected"]').val(n);
					createList();
			    }
			    countChecked();
				createList();
			    $("input:checkbox").click(countChecked);

			  });
			</script>
			
			
			
			""" )
		self.response.out.write("""
			<form action="/drinkers" method="post">
			<div>Drinker Name: <input type="text" name="drinker_name" /></div> """)
		## NEED TO CHANGE TO A SELECT MULTIPLE LIST (CHECKBOX)
		self.response. out.write("""
			<div>Select KegDroids Authorized  <br />
			""")
		self.response.out.write(kegdroid_list)
		self.response.out.write(""" 
			<div>Selected<input type="text" name="selected_kegdroid" size="3" /></div> 
			""")
		self.response.out.write(""" 
			<div>NumSelected<input type="text" name="num_selected" size="3" /></div>
			 """)
		self.response.out.write("""
			<div><input type="submit" value="Create Drinker"></div>
			</div>
			</form>""")
		self.response.out.write('</body></html>')

app = webapp2.WSGIApplication([
	('/drinkers/add', AddDrinkerHandler), 
	('/drinkers', DrinkerHandler)
   
], debug=True)
